<!-- @format -->

<!--
 - MineAdmin is committed to providing solutions for quickly building web applications
 - Please view the LICENSE file that was distributed with this source code,
 - For the full copyright and license information.
 - Thank you very much for using MineAdmin.
 -
 - @Author X.Mo<root@imoi.cn>
 - @Link   https://gitee.com/xmo/mineadmin-vue
-->
<template>
	<div class="ma-content-block lg:flex justify-between p-4">
		<!-- <div class="lg:w-2/12 w-full h-full p-2 shadow left">
			<a-input-group class="mb-2 w-full" size="mini">
				<a-input
					placeholder="搜索公司"
					allow-clear
					@input="changeKeyword"
					@clear="resetData"
				/>
			</a-input-group>
			<div class="content">
				<div
					v-for="(item, index) in f_depts"
					:key="index"
					class="flex my-tree justify-between"
					@click="switchDept(item.id)"
					:class="{ active: currentId == item.id }"
				>

          <div>
            <span>
						{{ item.label }}
					</span>
          </div>

          <div class="flex">
            <a-button @click.stop="show(item.id)" v-if="item.id" type="text">
              详情
            </a-button>
            <a-button @click.stop="edit(item.id)" v-if="item.id" type="text">
              编辑
            </a-button>
          </div>

				</div>
			</div>
			<a-button class="w-full mt-2" type="primary" @click="add">
				
				<template #default> 新增 </template>
			</a-button>
		</div> -->

		<div class=" w-full ">
			<!-- CRUD 组件 -->
			<ma-crud :options="crud" :columns="columns" ref="crudRef">
				<!-- 状态列 -->
				<template #status="{ record }">
					<a-switch
						:checked-value="1"
						unchecked-value="2"
						@change="changeStatus($event, record.id)"
						:default-checked="record.status == 1"
					/>
				</template>
				<!-- 头像列 -->
				<template #avatar="{ record }">
					<a-avatar>
						<img
							:src="record.avatar || $url + 'avatar.jpg'"
							style="object-fit: cover"
						/>
					</a-avatar>
				</template>
				<!-- 操作列 -->
				<!-- <template #operationCell="{ record }">
					<a-link @click="addressTap(record)" v-auth="['prediction:address:dzgl']"> 地址管理</a-link>
					<div v-if="record.id == 1">
						<a-link @click="updateCache(record.id)" v-auth="['system:user:clearCache']"
							> 更新缓存</a-link
						>
					</div>
				</template> -->
				<!-- 操作列扩展 -->
				<template #operationAfterExtend="{ record }">
					<a-dropdown
						trigger="hover"
						v-if="record.id != 1 && !isRecovery"
						@select="selectOperation($event, record.id)"
					>
						<a-link>更多</a-link>
						<template #content>
							<a-doption value="updateCache" v-auth="['system:user:clearCache']"
								>更新缓存</a-doption
							>
							<a-doption value="setHomePage" v-auth="['system:user:setHomePage']"
								>设置首页</a-doption
							>
							<a-doption
								value="resetPassword"
								v-auth="['system:user:initUserPassword']"
								>重置密码</a-doption
							>
						</template>
					</a-dropdown>
				</template>
			</ma-crud>
		</div>

		<a-modal v-model:visible="setHomeVisible" @before-ok="saveHomePage">
			<template #title>设置用户后台首页</template>
			<a-form-item label="用户首页">
				<a-select v-model="homePage" placeholder="请选择用户首页">
					<a-option
						v-for="(item, index) in homePageList"
						:key="index"
						:value="item.key"
					>
						{{ item.title }}
					</a-option>
				</a-select>
			</a-form-item>
		</a-modal>
		<a-drawer :footer="false" :width="1220" v-model:visible="visibleAddress">
			<template #title> 地址管理 </template>
			<addressVue ref="address" />
		</a-drawer>
		<ma-form-modal
			:column="f_columns"
			:submit="submit"
			ref="addFormRef"
			width="600px"
		>
		</ma-form-modal>
    <ShowModal
      ref="showModal"
    />
	</div>
</template>

<script setup>
	import { ref, onMounted, reactive, computed, watch } from "vue";
	import MaTreeSlider from "@cps/ma-treeSlider/index.vue";
	import dept from "@/api/system/dept";
	import user from "@/api/system/user";
	import commonApi from "@/api/common";
	import { Message, Modal } from "@arco-design/web-vue";
	import addressVue from "@/views/prediction/address/index.vue";
	import MaFormModal from "@/components/ma-form-modal/index.vue";
	import ShowModal from "./show.vue"
	import { request } from "@/utils/request.js";

	const AddMoneyModal = ref()
	const depts = ref([]);
	const currentId = ref(0);
	const homePageList = ref([]);
	const crudRef = ref();

	const setHomeVisible = ref(false);
	const userid = ref();
	const homePage = ref("");
	const address = ref();
	const visibleAddress = ref(false);

	onMounted(() => {
		getDepts();
		getDeptList()
		commonApi
			.getDict("dashboard")
			.then((res) => (homePageList.value = res.data));
	});
	// system/dept/remote
	const getDeptList = ()=>{
		request({    //  获取公司列表
            url: 'system/dept/remote',
            method: 'post',
            data:{
                openPage: false,
				remoteOption:{
					filter: {
						type: ["=", 2],
					},
				}
            }
        }).then(res=>{
            console.log('公司列表：',res)
        })
	}


  const showModal = ref(null)
  const show = async (id) => {
    showModal.value.open(id)
  }

	let isRecovery = computed(() =>
		crudRef.value ? crudRef.value.isRecovery : false
	);

	function getDepts() {
		dept.treePt().then((res) => {
			depts.value = res.data;
			depts.value.unshift({ label: "所有部门", id: 0 });
		});
	}

	const addressTap = (row) => {
		address.value.open(row);
		visibleAddress.value = true;
	};

	const switchDept = (id) => {
		currentId.value = id;
		crudRef.value.requestParams = { dept_id: id };
		crudRef.value.requestData();
	};

	const changeStatus = async (status, id) => {
		const response = await user.changeStatus({ id, status });
		if (response.success) {
			Message.success(response.message);
		}
	};

	const updateCache = (id) => {
		user.clearCache(id).then((res) => {
			if (res.success) Message.success(res.message);
		});
	};

	const resetPassword = (id) => {
		user
			.initUserPassword({ id })
			.then((res) => res.success && Message.success(res.message));
	};

	const saveHomePage = (done) => {
		user
			.setHomePage({ id: userid.value, dashboard: homePage.value })
			.then((res) => {
				res.success && Message.success(res.message);
			});
		done(true);
	};

	const selectOperation = (value, id) => {
		if (value === "resetPassword") {
			Modal.info({
				title: "提示",
				content: "确定将该用户密码重置为 123456 吗？",
				simple: false,
				onBeforeOk: (done) => {
					resetPassword(id);
					done(true);
				},
			});
			return;
		}

		if (value === "updateCache") {
			updateCache(id);
			return;
		}

		if (value === "setHomePage") {
			setHomeVisible.value = true;
			userid.value = id;
			return;
		}
	};

	const crud = reactive({
		api: user.getPageList_event,
		recycleApi: user.getRecyclePageList,
		searchColNumber: 6,
		showIndex: false,
		pageLayout: "fixed",
		rowSelection: { showCheckedAll: true },
		operationColumn: true,
		operationWidth: 200,
		add: { show: true, api: user.save, auth: ["system:user:save"] },
		edit: { show: true, api: user.update, auth: ["system:user:update"] },
		delete: {
			show: true,
			api: user.deletes,
			auth: ["system:user:delete"],
			realApi: user.realDeletes,
			realAuth: ["system:user:realDeletes"],
		},
		recovery: {
			show: true,
			api: user.recoverys,
			auth: ["system:user:recovery"],
		},
		import: {
			show: true,
			url: "system/user/import",
			templateUrl: "system/user/downloadTemplate",
			auth: ["system:user:import"],
		},
		export: {
			show: true,
			url: "system/user/export",
			auth: ["system:user:export"],
		},
		formOption: {
			width: 800,
			layout: [
				{
					formType: "grid",
					cols: [{ span: 24, formList: [{ dataIndex: "avatar" }] }],
				},
				{
					formType: "grid",
					cols: [
						{ span: 12, formList: [{ dataIndex: "username" }] },
						{ span: 12, formList: [{ dataIndex: "dept_ids" }] },
					],
				},
				{
					formType: "grid",
					cols: [
						{ span: 12, formList: [{ dataIndex: "password" }] },
						{ span: 12, formList: [{ dataIndex: "nickname" }] },
					],
				},
				{
					formType: "grid",
					cols: [
						{ span: 12, formList: [{ dataIndex: "role_ids" }] },
						{ span: 12, formList: [{ dataIndex: "phone" }] },
					],
				},
				// { formType: 'grid', cols: [ { span: 12, formList: [ { dataIndex: 'post_ids' }] }, { span: 12, formList: [{ dataIndex: 'email' }] }]  },
				{
					formType: "grid",
					cols: [{ span: 24, formList: [{ dataIndex: "wx_user_type" }] }],
				},
				{
					formType: "grid",
					cols: [{ span: 24, formList: [{ dataIndex: "status" }] }],
				},
				{
					formType: "grid",
					cols: [{ span: 24, formList: [{ dataIndex: "remark" }] }],
				},
			],
		},
		// isDbClickEdit: false,
		beforeOpenEdit: (record) => {
			if (record.id === 1) {
				Message.error("创始人不可编辑");
				return false;
			}
			return true;
		},
		beforeDelete: (ids) => {
			if (ids.includes(1)) {
				Message.error("创始人不可删除");
				return false;
			}
			return true;
		},
		beforeRequest:(row) => {
		    row.wx_user_type = '8'
		}
	});

	const columns = reactive([
		{
			title: "ID",
			dataIndex: "id",
			addDisplay: false,
			editDisplay: false,
			width: 50,
			hide: true,
		},
		{
			title: "头像",
			dataIndex: "avatar",
			width: 75,
			formType: "upload",
			returnType: "url",
			type: "image",
			rounded: true,
			labelWidth: "86px",
		},
		{
			title: "账户",
			dataIndex: "username",
			width: 130,
			search: true,
			addDisabled: false,
			editDisabled: true,
			commonRules: [{ required: true, message: "账户必填" }],
		},
		{
			title: "所属公司",
			dataIndex: "dept_ids",
			hide: true,
			formType: "tree-select",
			multiple: false,
			treeCheckable: false,
			treeCheckStrictly: true,
			dict: { url: "system/dept/treePt" },
			commonRules: [{ required: true, message: "所属公司必选" }],
			editDefaultValue: async (record) => {
				const response = await user.read(record.id);
				return response.data.deptList.map((item) => item.id);
			},
		},
		{
			title: "密码",
			dataIndex: "password",
			hide: true,
			autocomplete: "off",
			addDefaultValue: "123456",
			editDefaultValue: "",
			addDisabled: false,
			editDisabled: true,
			type: "password",
			addRules: [{ required: true, message: "密码必填" }],
		},
		{ title: "姓名", dataIndex: "nickname", width: 120, search: true },
		{
			title: "角色",
			dataIndex: "role_ids",
			width: 120,
			formType: "select",
			multiple: true,
			dict: { url: "system/role/list", props: { label: "name", value: "id" } },
			hide: true,
			commonRules: [{ required: true, message: "角色必选" }],
			editDefaultValue: async (record) => {
				const response = await user.read(record.id);
				return response.data.roleList.map((item) => item.id);
			},
		},
		{
			title: "手机",
			dataIndex: "phone",
			width: 150,
			search: true,
			commonRules: [
				{
					match: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
					message: "请输入正确的手机号码",
				},
			],
		},
		// {
		//   title: '岗位', dataIndex: 'post_ids', width: 120, formType: 'select', multiple: true,
		//   dict: { url: 'system/post/list', props: { label: 'name', value: 'id' } }, hide: true,
		//   editDefaultValue: async (record) => {
		//     const response = await user.read(record.id)
		//     const ids = response.data.postList.map(item => item.id )
		//     return ids
		//   }
		// },
		// {
		//   title: '邮箱', dataIndex: 'email', width: 200, search: true,
		//   commonRules: [{ type: 'email', message: '请输入正确的邮箱' }]
		// },
		// {
		//   title: '用户类型', dataIndex: 'user_type', width: 100, search: true, formType: 'radio',
		//   dict: {
		//     name: 'user_type',
		//     props: { label: 'title', value: 'key' }, translation: true,
		//     tagColors: { '100': 'orange', '200': 'blue', '300': 'green'}
		//   },
		//   addDefaultValue: '100', labelWidth: '86px'
		// },
		{
			title: "用户类别",
			dataIndex: "wx_user_type",
			formType: "radio",
			search: true,
			addDefaultValue: "1",
			dict: {
				data: [
					{
						label: "安全端",
						value: "8",
					},
				],
				translation: true,
			},
		},
		{
			title: "状态",
			dataIndex: "status",
			width: 100,
			search: true,
			formType: "radio",
			dict: { name: "data_status", props: { label: "title", value: "key" } },
			addDefaultValue: "1",
			labelWidth: "86px",
		},
		// {
		// 	title: "是否接收每日短信",
		// 	dataIndex: "is_sms",
		// 	width: 140,
		// 	search: true,
		// 	formType: "radio",
		// 	addDefaultValue: "0",
		// 	dict: {
		// 		data: [
		// 			{
		// 				label: "否",
		// 				value: "0",
		// 			},
		// 			{
		// 				label: "是",
		// 				value: "1",
		// 			},
		// 		],
		// 		translation: true,
		// 	},
		// 	labelWidth: "146px",
		// },
		{
			title: "备注",
			dataIndex: "remark",
			width: 180,
			hide: true,
			formType: "textarea",
			labelWidth: "86px",
		},
		{
			title: "注册时间",
			dataIndex: "created_at",
			width: 180,
			addDisplay: false,
			editDisplay: false,
			search: true,
			formType: "range",
		},
	]);

	// 搜索相关
	const selectedKeys = ref("");

	function changeKeyword(keyword) {
		selectedKeys.value = keyword;
	}

	function resetData() {
		selectedKeys.value = "";
	}

	const f_depts = computed(() => {
		return depts?.value.filter((item) =>
			item.label.includes(selectedKeys.value)
		);
	});

	const addFormRef = ref("");

	const sumbitType = ref("");

	function edit(e) {
		sumbitType.value = update;
		dept.getList().then((res) => {
			res.data.forEach((item) => {
				if (item.id == e) {
					addFormRef.value.open(item);
					return;
				}
			});
		});
	}

	function add() {
		sumbitType.value = save;
		addFormRef.value.open({
			created_at: undefined,
			created_by: undefined,
			leader: undefined,
			level: undefined,
			name: undefined,
			parent_id: undefined,
			phone: undefined,
			remark: undefined,
			sort: 0,
			status: "1",
			type: "2",
			updated_at: undefined,
			updated_by: 1,
		});
	}

	// 表单
	const submit = async (formData) => {
		sumbitType.value(formData).then((res) => {
			init();
		});
	};

	function save(formData) {
		dept.save(formData).then((res) => {
			init();
		});
	}

	function update(formData) {
		dept.update(formData.id, formData).then((res) => {
			init();
		});
	}

	function init() {
		addFormRef.value.close();
		depts.value = [];
		getDepts();
	}

	const f_columns = reactive([
		{
			title: "企业名称",
			dataIndex: "name",
			search: true,
			width: 150,
			align: "center",
			rules: [{ required: true, message: "部门名称必填" }],
		},
		{
			title: "负责人",
			dataIndex: "leader",
			search: true,
			align: "center",
			width: 120,
		},
		{
			title: "手机",
			dataIndex: "phone",
			align: "center",
			search: true,
			width: 150,
			rules: [
				{
					match: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
					message: "请输入正确的手机号码",
				},
			],
		},
		// { title: '暂存超期天数', dataIndex: 'zc_day',  align:'center',width: 120,formType:'input' },
    	// { title: '仓储超期天数', dataIndex: 'cc_day', align:'center',width: 120,formType:'input' },
		{
			title: "排序",
			dataIndex: "sort",
			align: "center",
			formType: "input-number",
			addDefaultValue: 1,
			width: 180,
			min: 0,
			max: 1000,
		},
		{
			title: "企业类型",
			dataIndex: "type",
			align: "center",
			search: true,
			formType: "radio",
			addDefaultValue: '1',
			width: 120,
			dict: {
				data: [
					// {
					// label: "园区企业",
					// value: '1'
					// },
					{
					label: "用户企业",
					value: '2'
					}
				],
				translation: true
			}
		},
		{
			title: "状态",
			dataIndex: "status",
			align: "center",
			search: true,
			formType: "radio",
			dict: { name: "data_status", props: { label: "title", value: "key" } },
			addDefaultValue: "1",
			width: 120,
		},
		{
			title: "备注",
			dataIndex: "remark",
			align: "center",
			hide: true,
			formType: "textarea",
		},
		
	]);
</script>

<script>
	export default { name: "system:user" };
</script>

<style scoped lang="less">
	.ma-content-block {
		height: 100%;
		> .left {
			height: 100%;
			overflow: hidden;
			display: flex;
			flex-direction: column;

			> div {
				flex: 0 0 auto;
			}

			.content {
				flex: 1 1 auto;
				overflow: hidden scroll;

				&::-webkit-scrollbar {
					width: 6px; /*高宽分别对应横竖滚动条的尺寸*/
					height: 7px;
				}

				&::-webkit-scrollbar-thumb {
					border-radius: 10px;
					background: var(--color-text-4);
				}
				&::-webkit-scrollbar-thumb:hover {
					border-radius: 10px;
					background: var(--color-text-3);
				}
				&::-webkit-scrollbar-track {
					border-radius: 0;
					background: var(--color-text-5);
				}
			}
		}
	}

	.my-tree {
		display: flex;
		flex-wrap: nowrap;
		align-items: center;
		color: var(--color-text-1);
		cursor: pointer;
		min-height: 32px;
		padding: 5px 10px;
		font-size: 14px;
		justify-content: space-between;
		// padding-left: 18px;
		box-sizing: border-box;

		&:hover {
			background-color: var(--color-fill-2);
			border-radius: 3px;
		}

		&.active {
			color: rgb(var(--primary-6));
			transition: color 0.2s cubic-bezier(0, 0, 1, 1);
		}
	}
</style>
